<template>
  <view>
    <!-- 通知列表弹出框 -->
    <up-popup 
      :show="show" 
      mode="top" 
      @close="closePopup"
      :round="10"
      :safeAreaInsetTop="true"
      zIndex="10076"
    >
      <view class="notification-popup">
        <view class="popup-header">
          <text class="header-title">系统通知</text>
          <up-icon 
            name="close" 
            size="20" 
            color="#999" 
            @click="closePopup"
            class="close-icon"
          ></up-icon>
        </view>
        
        <view class="notification-list">
          <scroll-view 
            class="notification-scroll" 
            scroll-y="true" 
            v-if="notifications.length > 0"
          >
            <view 
              v-for="notification in notifications" 
              :key="notification.notification_id"
              class="notification-item"
              :class="{ 'unread': !isNotificationRead(notification) }"
              @click="markAsRead(notification)"
            >
              <view class="notification-content">
                <text class="notification-title">{{ notification.title || '无标题' }}</text>
                <text class="notification-text">{{ notification.content }}</text>
              </view>
              <view class="notification-footer">
                <text class="notification-time">{{ formatNotificationTime(notification.created_at) }}</text>
                <up-tag 
                  v-if="!isNotificationRead(notification)" 
                  text="未读" 
                  type="error" 
                  size="mini" 
                  plain
                ></up-tag>
              </view>
            </view>
          </scroll-view>
          
          <view class="empty-notification" v-else>
            <up-empty 
              text="暂无通知" 
              mode="message" 
              iconSize="80"
              textSize="28"
            ></up-empty>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { getNotificationListAll } from '@/api/notification/index';
import { formatTime, parseDate } from '@/utils/index';
import { useSystemNotificationStore } from '@/stores/system_notification';
import websocket from '@/utils/websocket';

// 定义属性
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  }
});

// 获取系统通知 store 实例
const systemNotificationStore = useSystemNotificationStore();

// 定义事件
const emit = defineEmits(['update:show', 'close']);

// 通知列表数据
const notifications = ref([]);

// 关闭弹出框
const closePopup = () => {
  emit('update:show', false);
  emit('close');
};

// 格式化通知时间
const formatNotificationTime = (time) => {
  if (!time) return '';
  return formatTime(parseDate(time), 'MM-DD HH:mm');
};

// 标记为已读
const markAsRead = async (notification) => {
  // 通过WebSocket发送已读确认消息
  const readData = {
    type: 'system_notification_read',
    msg: '发送系统通知已读',
    notificationId: notification.notification_id
  };
  websocket.sendMessage(readData);
};

// 检查通知是否已读
const isNotificationRead = (notification) => {
  // 如果有receive_users字段，根据后端逻辑检查已读状态
  if (notification.receive_users) {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.user_id) {
      const userId = userInfo.user_id;
      // 检查该用户是否在receive_users中，并且已读
      return notification.receive_users[userId] && notification.receive_users[userId].read;
    }
  }
  // 对于广播通知或其他情况，使用原来的is_read字段
  return notification.is_read || false;
};

// 获取通知列表
const fetchNotifications = async () => {
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    const res = await getNotificationListAll({});
    uni.hideLoading();
    
    if (res.code === 200) {
      // 根据后端代码，getNotificationListAll 直接返回通知数组
      // API返回的数据结构是 { code: 200, data: [...] }
      notifications.value = (res.data || []).map(notification => ({
        ...notification
      }));
      
      // 更新 store 中的通知列表和未读计数
      systemNotificationStore.setNotifications(notifications.value);
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取通知列表异常:', error);
  }
};

// 监听弹出框显示状态变化
watch(() => props.show, (newVal) => {
  if (newVal) {
    fetchNotifications();
  }
});

// 获取通知列表
onShow(() => {
  if (props.show) {
    fetchNotifications();
  }
});
</script>

<style scoped lang="scss">
.notification-popup {
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-icon {
  padding: 10rpx;
}

.notification-list {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.notification-scroll {
  flex: 1;
  max-height: 60vh;
  overflow: auto;
}

.notification-item {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f5f5f5;
  transition: background-color 0.3s;
  box-shadow: none; // 移除阴影
}

.notification-item:hover {
  background-color: #f9f9f9;
}

.notification-item.unread {
  background-color: #f0f8ff;
  box-shadow: none; // 确保未读项目也没有阴影
}

.notification-content {
  margin-bottom: 10rpx;
}

.notification-title {
  display: block;
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.notification-text {
  display: block;
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 10rpx;
}

.notification-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-time {
  font-size: 24rpx;
  color: #999;
}

.empty-notification {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>